﻿using System;
using System.Linq;
using System.Web;

namespace MvcFriendlyModule
{
    public class MvcFriendlyModule2 : IHttpModule
    {
        #region IHttpModule Members

        void IHttpModule.Dispose()
        {
        }

        void IHttpModule.Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        #endregion

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            var form = app.Context.Request.Form;

            form.GetType().GetProperty("IsReadOnly",
                System.Reflection.BindingFlags.Instance |
                System.Reflection.BindingFlags.NonPublic)
                .SetValue(form, false, null);

            foreach (var key in form.AllKeys)
            {
                if (key.Contains("$"))
                {
                    var value = form[key];
                    form.Remove(key);
                    var newKey = key.Substring(key.LastIndexOf("$") + 1);
                    form.Add(newKey, value);
                }
                else if(key == "__VIEWSTATE" || key == "__EVENTVALIDATION" || key == "__EVENTTARGET" || key == "__EVENTARGUMENT")
                {
                    form.Remove(key);
                }
            }
        }
    }
}